import React, { useEffect, useState } from 'react';
import {
  Box,
  Typography,
  Grid,
  Container,
  TextField,
  InputAdornment,
} from '@mui/material';
import SearchIcon from '@mui/icons-material/Search';
import { useNavigate } from 'react-router-dom';
import { Implementation } from '../types';
import { api } from '../services/api';
import ImplementationCard from '../components/CodeImplementation/ImplementationCard';

const HomePage: React.FC = () => {
  const navigate = useNavigate();
  const [recentImplementations, setRecentImplementations] = useState<Implementation[]>([]);
  const [searchQuery, setSearchQuery] = useState('');

  useEffect(() => {
    // 加载最新的实现
    const loadRecentImplementations = async () => {
      const categories = await api.getCategories();
      const implementations: Implementation[] = [];
      
      for (const category of categories) {
        const categoryImplementations = await api.getCategoryImplementations(category.id);
        implementations.push(...categoryImplementations);
      }
      
      // 按更新时间排序，获取最新的10个
      const sorted = implementations.sort(
        (a, b) => new Date(b.metadata.updateTime).getTime() - new Date(a.metadata.updateTime).getTime()
      ).slice(0, 10);
      
      setRecentImplementations(sorted);
    };

    loadRecentImplementations();
  }, []);

  const handleSearch = (event: React.KeyboardEvent<HTMLInputElement>) => {
    if (event.key === 'Enter' && searchQuery.trim()) {
      navigate(`/search?q=${encodeURIComponent(searchQuery.trim())}`);
    }
  };

  return (
    <Container maxWidth="lg">
      {/* 搜索框 */}
      <Box sx={{ my: 4, textAlign: 'center' }}>
        <Typography variant="h4" component="h1" gutterBottom>
          技术实现代码库
        </Typography>
        <Typography variant="subtitle1" color="text.secondary" paragraph>
          探索、学习和分享各种技术的实现方案
        </Typography>
        <TextField
          fullWidth
          variant="outlined"
          placeholder="搜索技术实现..."
          value={searchQuery}
          onChange={(e) => setSearchQuery(e.target.value)}
          onKeyPress={handleSearch}
          sx={{ maxWidth: 600, mt: 2 }}
          InputProps={{
            startAdornment: (
              <InputAdornment position="start">
                <SearchIcon />
              </InputAdornment>
            ),
          }}
        />
      </Box>

      {/* 最新实现 */}
      <Box sx={{ my: 4 }}>
        <Typography variant="h5" gutterBottom>
          最新实现
        </Typography>
        <Grid container spacing={3}>
          {recentImplementations.map((implementation) => (
            <Grid item xs={12} sm={6} md={4} key={implementation.id}>
              <ImplementationCard implementation={implementation} />
            </Grid>
          ))}
        </Grid>
      </Box>
    </Container>
  );
};

export default HomePage;
